package manage.controller;

import commons.LayuiResult;
import commons.TreeNode;
import entity.Permission;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import manage.service.PermissionService;
import manage.service.RoleService;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vo.RoleVo;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/role")
@Api(tags = "角色相关模块")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 加载所有角色
     * @param roleVo
     * @return
     */
    @GetMapping("/loadAllRoles")
    @RequiresPermissions("role:select")
    @ApiOperation(value = "角色列表")
    @ApiImplicitParam(name = "roleVo",value = "角色实体Vo",required = true,dataType = "RoleVo")
    public LayuiResult loadAllRoles(RoleVo roleVo){
        LayuiResult layuiResult = roleService.loadAllRoles(roleVo);
        return layuiResult;
    }


    /**
     * 加载某个角色下的所有权限
     * @param roleId
     * @return
     */
    @GetMapping("/initPermissionsByRoleId")
    @RequiresPermissions("role:select")
    @ApiOperation(value = "加载某个角色下的所有权限")
    @ApiImplicitParam(name = "roleId",value = "角色ID",required = true,dataType = "Integer")
    public LayuiResult initRolePermissionsByRoleId(Integer roleId) {
        LayuiResult layuiResult = permissionService.initRolePermissionsByRoleId(roleId);
        return layuiResult;
    }

    /**
     * 保存角色和权限
     * @param rId
     * @param pIds
     * @return
     */
    @PostMapping("/saveRolePermission")
    @RequiresPermissions("role:update")
    @ApiOperation(value = "保存角色和权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rId",value = "角色ID",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "pIds",value = "权限ID数组",required = true,dataType = "Array"),
    })
    public LayuiResult saveRolePermission(@Param("rId") Integer rId, @Param("pIds") Integer[] pIds) {
        //保存角色和权限
        int i = roleService.saveRolePermission(rId, pIds);
        LayuiResult layuiResult = new LayuiResult();
        if (i > 0){
            layuiResult = LayuiResult.success(0, "分配成功");
        }else {
            layuiResult = LayuiResult.fail(-1, "分配失败");
        }
        return layuiResult;
    }
}
